#include "MainFrame.h"

//(*InternalHeaders(MainFrame)
#include <wx/intl.h>
#include <wx/string.h>
//*)

#include "WebSync.h"

#define SQLITE_DATABASE_FILE_LOCATION "database"
#define SQLITE_INIT_SCRIPT_LOCATION "db.sql"

#define PAGE_VIEW_BUFFER_LENGTH 30

//(*IdInit(MainFrame)
const long MainFrame::ID_LISTCTRL1 = wxNewId();
const long MainFrame::ID_BUTTON1 = wxNewId();
const long MainFrame::ID_BUTTON2 = wxNewId();
const long MainFrame::ID_BUTTON5 = wxNewId();
const long MainFrame::ID_TEXTCTRL1 = wxNewId();
const long MainFrame::ID_BUTTON10 = wxNewId();
const long MainFrame::ID_BUTTON4 = wxNewId();
const long MainFrame::ID_TEXTCTRL2 = wxNewId();
const long MainFrame::ID_MENUITEM1 = wxNewId();
//*)


BEGIN_EVENT_TABLE(MainFrame,wxFrame)
	//(*EventTable(MainFrame)
	//*)
END_EVENT_TABLE()

MainFrame::MainFrame(wxWindow* parent,wxWindowID id,const wxPoint& pos,const wxSize& size)
{
	//(*Initialize(MainFrame)
	Create(parent, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE|wxSUNKEN_BORDER|wxVSCROLL, _T("wxID_ANY"));
	SetClientSize(wxSize(738,549));
	ListCtrl1 = new wxListCtrl(this, ID_LISTCTRL1, wxPoint(16,48), wxSize(704,376), wxLC_REPORT|wxLC_EDIT_LABELS|wxVSCROLL, wxDefaultValidator, _T("ID_LISTCTRL1"));
	Button1 = new wxButton(this, ID_BUTTON1, _("上一页"), wxPoint(16,440), wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON1"));
	Button2 = new wxButton(this, ID_BUTTON2, _("下一页"), wxPoint(632,440), wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON2"));
	Button5 = new wxButton(this, ID_BUTTON5, _("历史"), wxPoint(512,496), wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON5"));
	TextCtrl1 = new wxTextCtrl(this, ID_TEXTCTRL1, wxEmptyString, wxPoint(280,440), wxDefaultSize, 0, wxDefaultValidator, _T("ID_TEXTCTRL1"));
	Button10 = new wxButton(this, ID_BUTTON10, _("跳转"), wxPoint(368,440), wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON10"));
	Button4 = new wxButton(this, ID_BUTTON4, _("刷新"), wxPoint(144,496), wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON4"));
	TextCtrl2 = new wxTextCtrl(this, ID_TEXTCTRL2, wxEmptyString, wxPoint(568,8), wxSize(152,27), 0, wxDefaultValidator, _T("ID_TEXTCTRL2"));
	MenuBar1 = new wxMenuBar();
	Menu1 = new wxMenu();
	MenuItem1 = new wxMenuItem(Menu1, ID_MENUITEM1, _("设置目录"), wxEmptyString, wxITEM_NORMAL);
	Menu1->Append(MenuItem1);
	MenuBar1->Append(Menu1, _("导入"));
	SetMenuBar(MenuBar1);

	Connect(ID_BUTTON1,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&MainFrame::OnPreviousPage);
	Connect(ID_BUTTON2,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&MainFrame::OnNextPage);
	Connect(ID_BUTTON5,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&MainFrame::OnReadHistory);
	Connect(ID_BUTTON10,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&MainFrame::OnJumpPage);
	Connect(ID_BUTTON4,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&MainFrame::OnImportRefresh);
	Connect(ID_TEXTCTRL2,wxEVT_COMMAND_TEXT_UPDATED,(wxObjectEventFunction)&MainFrame::OnKeywordSearch);
	Connect(ID_TEXTCTRL2,wxEVT_COMMAND_TEXT_ENTER,(wxObjectEventFunction)&MainFrame::OnKeywordSearch);
	Connect(ID_MENUITEM1,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&MainFrame::OnClickSetDirectory);
	//*)

    Move(wxPoint(250,70));

/*
	MenuFile = new wxMenu;
    MenuFile->Append(LIST_ABOUT, _T("&About"));
    MenuFile->AppendSeparator();
    MenuFile->Append(LIST_QUIT, _T("E&xit\tAlt-X"));

	MenuImport = new wxMenu();
	MenuImport->Append(LIST_IMPORT, _T("&Import"));

	MenuBar1->Append(MenuFile, _("File"));
	MenuBar1->Append(MenuImport, _("Import"));
*/

    TextCtrl1->Clear();

	ThisDatabase = new DBSqlite(SQLITE_DATABASE_FILE_LOCATION,SQLITE_INIT_SCRIPT_LOCATION);
#ifdef _DEBUG
    ThisDatabase->InitTables();
#endif

    ThisAction = new Action(ThisDatabase);

    DlgHistory = new DialogReadHistory(this,ThisAction);
    /*DialogSetDialog* DlgFileChooser = new DialogSetDialog(this);
    DlgFileChooser->Show(true);*/

    InitListCtrl();
    ImportRefresh();
}

MainFrame::~MainFrame()
{
	//(*Destroy(MainFrame)
	//*)
	delete ThisDatabase;
    delete ThisAction;

    delete DlgHistory;
}

void MainFrame::HideAllDialogs()
{
    /*
    DlgStatus->Show(false);
    DlgInfo->Show(false);
    DlgNoteList->Show(false);
    DlgReviewList->Show(false);
    DlgSync->Show(false);
    */
    DlgHistory->Show(false);
}

void MainFrame::InitListCtrl()
{
    int shift = 0;

    wxListItem itemCol;

    itemCol.SetText(_T("书ID"));
    itemCol.SetImage(-1);
    ListCtrl1->InsertColumn(0, itemCol);

    itemCol.SetText(_T("书名"));
    itemCol.SetImage(-1);
    ListCtrl1->InsertColumn(1, itemCol);

    itemCol.SetText(_T("状态"));
    itemCol.SetAlign(wxLIST_FORMAT_CENTRE);
    ListCtrl1->InsertColumn(2, itemCol);

    itemCol.SetText(_T("页数"));
    itemCol.SetAlign(wxLIST_FORMAT_RIGHT);
    ListCtrl1->InsertColumn(3, itemCol);

    ListCtrl1->SetColumnWidth(0, 50);
    ListCtrl1->SetColumnWidth(1, 490);
    ListCtrl1->SetColumnWidth(2, 80);
    ListCtrl1->SetColumnWidth(3, 80);
    //ListCtrl1->SetColumnWidth(2, wxLIST_AUTOSIZE);
    //ListCtrl1->SetColumnWidth(3, wxLIST_AUTOSIZE);
}

void MainFrame::RefreshBookList()
{
    uint32_t listcount = g_pool.InfoList->GetBookCount();

    bplog(LOG_LEVEL_DEBUG,"MainFrame:Now refresh book shelf on GUI, InfoList has %u books",listcount);

    ListCtrl1->DeleteAllItems();
    BookInfo* list = g_pool.InfoList->GetListPtr();
    for(int i=0; i<listcount; i++)
    {
        wxString buf;
        string str;
        int j;
        long tmp = 0;

        j = list[i].BookID;
        buf.Printf(_T("%d"),j);
        //bplog(LOG_LEVEL_DEBUG,"MainFrame:now insert item %d, column 0, text:%s",i,(char *)buf.char_str());
        tmp = ListCtrl1->InsertItem(i, buf, 0);
        ListCtrl1->SetItemData(tmp, i);

        str = list[i].BookName;
        buf = wxString(str.c_str(), wxConvUTF8);
        //bplog(LOG_LEVEL_DEBUG,"MainFrame:now insert item %d, column 1, text:%s",i,(char *)buf.char_str());
        ListCtrl1->SetItem(tmp, 1, buf);

        str = BookInfo::StatusToString(list[i].BookStatus);
        buf = wxString(str.c_str(), wxConvUTF8);
        //bplog(LOG_LEVEL_DEBUG,"MainFrame:now insert item %d, column 2, text:%s",i,(char *)buf.char_str());
        ListCtrl1->SetItem(tmp, 2, buf);

        j = list[i].PageCount;
        buf.Printf(_T("%d"),j);
        //bplog(LOG_LEVEL_DEBUG,"MainFrame:now insert item %d, column 3, text:%s",i,(char *)buf.char_str());
        ListCtrl1->SetItem(tmp, 3, buf);
    }
}

void MainFrame::RefreshPageView()
{
    uint32_t page;
    wxString string;
    char text[PAGE_VIEW_BUFFER_LENGTH] = {0};

    page = g_pool.InfoList->GetCurrentPage();

    sprintf(text,"第%d页",page);
    string = wxString::FromUTF8(text);

    TextCtrl1->Clear();
    TextCtrl1->WriteText(string);
}

void MainFrame::OnPreviousPage(wxCommandEvent& event)
{
    ThisAction->ReadPreviousPage();

    RefreshBookList();
    RefreshPageView();
}

void MainFrame::OnNextPage(wxCommandEvent& event)
{
    ThisAction->ReadNextPage();

    RefreshBookList();
    RefreshPageView();
}

void MainFrame::OnJumpPage(wxCommandEvent& event)
{
    wxString string = TextCtrl1->GetValue();
    string = string.SubString(1,string.length()-1);
    int page = atoi((char *)string.char_str());
    wxString string2 = TextCtrl2->GetValue();

    bplog(LOG_LEVEL_DEBUG,"MainFrame:string=%s",(char *)string.char_str());
    bplog(LOG_LEVEL_DEBUG,"MainFrame:Keyword is:%s,page=%d",(char *)string2.char_str(),page);

    if(page >= 1)
    {
        ThisAction->ReadPage(page,(char *)string2.char_str());
        RefreshBookList();
        RefreshPageView();
    }
}

void MainFrame::OnTestImport(wxCommandEvent& event)
{
    /*
    wxString title = wxString::FromUTF8("title");
    wxString confirm = wxString::FromUTF8("confirm");

    wxMessageBox(title,confirm,wxYES_NO|wxCANCEL,this);

    for ( int i = 0; i < NUM_ITEMS; i++ )
    {
        BookList->InsertItem(i, wxString::Format(_T("Item %d 0"), i), 1);
        BookList->SetItem(i, 1, wxString::Format(_T("Item %d 1"), i));
    }
    */

    wxString string2 = TextCtrl2->GetValue();

    bplog(LOG_LEVEL_DEBUG,"MainFrame:go Import");
    ThisAction->ImportBooksFromDirectory("/home/frank/bptest/");
    ThisAction->ReadPage(1,(char *)string2.char_str());

    RefreshBookList();
    RefreshPageView();

    //test sync with douban
    /*
    DoubanSync* sync = new DoubanSync();
    sync->RequestToken();
    */
}

void MainFrame::OnStatusClick(wxCommandEvent& event)
{
    HideAllDialogs();
    DlgStatus->Show(true);
}

void MainFrame::OnReadHistory(wxCommandEvent& event)
{
    long index = -1;
    wxString StrBookID;

    HideAllDialogs();

    index = ListCtrl1->GetNextItem(index,wxLIST_NEXT_ALL,wxLIST_STATE_SELECTED);
    if(index == -1)
    {
        wxString title = wxString::FromUTF8("Please select at least on row");
        wxString confirm = wxString::FromUTF8("OK");
        wxMessageBox(title,confirm,wxOK,this);
        return;
    }

    bplog(LOG_LEVEL_DEBUG,"MainFrame:index is %d",index);

    StrBookID = ListCtrl1->GetItemText(index);

    bplog(LOG_LEVEL_DEBUG,"MainFrame:Book ID by which to get read history is %s",(char *)StrBookID.char_str());

    DlgHistory->SetBookID(atoi(StrBookID.char_str()));
    DlgHistory->RefreshHistoryList(false);
    DlgHistory->Show(true);
}

void MainFrame::OnNoteClick(wxCommandEvent& event)
{
    HideAllDialogs();
    DlgNoteList->Show(true);
}

void MainFrame::OnRiviewClick(wxCommandEvent& event)
{
    HideAllDialogs();
    DlgReviewList->Show(true);
}

void MainFrame::OnInfoClick(wxCommandEvent& event)
{
    HideAllDialogs();
    DlgInfo->Show(true);
}

void MainFrame::OnWebSync(wxCommandEvent& event)
{
    HideAllDialogs();
    DlgSync->Show(true);
}

void MainFrame::OnImportRefresh(wxCommandEvent& event)
{
    ImportRefresh();
}

void MainFrame::ImportRefresh()
{
    wxString string2 = TextCtrl2->GetValue();

    bplog(LOG_LEVEL_DEBUG,"MainFrame:go Import refresh");
    ThisAction->RefreshBooksFromDirectory();
    ThisAction->ReadPage(1,(char *)string2.char_str());

    RefreshBookList();
    RefreshPageView();
}

void MainFrame::OnKeywordSearch(wxCommandEvent& event)
{
    bplog(LOG_LEVEL_DEBUG,"MainFrame:go Keyword Search");
    OnJumpPage(event);
}

void MainFrame::OnClickSetDirectory(wxCommandEvent& event)
{
    DialogSetDirectory* DlgDirectory = new DialogSetDirectory(this,ThisDatabase);
    DlgDirectory->ShowModal();
    delete DlgDirectory;
}
